#include "test7.h"

/* hash */

void test7(void)
{
    int key[11] = {23,34,14,38,46,16,68,15,07,31,26};
    hashlist *hash;
    hash = HashCreate();
    // printf(" %d  ",hash->ha->key);
    for( int i = 0; i < 11; i++ ){
        HashInsert(hash, key[i]);
    }
    HashAllPrintf(hash);
    HashSearch(hash, 68);
}

hashlist *HashCreate(void)
{
    hashlist *h = (hashlist *)malloc(sizeof(hashlist));
    if(h == NULL){
        printf("malloc failure\n");
        return NULL;
    }
    memset(h, 0, sizeof(hashlist));
    return h;
}

int HashInsert(hashlist *list, int key)
{
    hashnode *s, *p;
    if(list == NULL){
        printf("list is null\n");
        return -1;
    }
    s = (hashnode *)malloc(sizeof(hashnode));
    s->key      = key;
    s->value    = Hash(key);
    s->next     = NULL;
    p = &(list->ha[s->value]);
    while( p->next != NULL && p->next->key < s->key){
        p = p->next;
    }
    s->next = p->next;
    p->next = s;
    printf("%d\n", p->next->key);
    printf("%d\n", p->next->value);
}

int HashSearch(hashlist *list, int key)
{
    if(list == NULL){
        printf("list is null\n");
        return -1;
    }
    int value = Hash(key);
    hashnode *s = &(list->ha[value]);
    while( s->next!=NULL && s->next->key!=key ){
        s = s->next;
    }
    if( s->next == NULL ){
        printf("no found\n");
        return -1;
    }
    else{
        printf("have found key in i=%d key=%d\n", value, key);
        return 0;
    }
}

int Hash(int key)
{
    return key%num;
}

int HashAllPrintf(hashlist *list)
{
    hashnode *s;
    if(list == NULL){
        printf("list is null\n");
        return -1;
    }
    for( int i=0; i<num; i++ ){
        s = &(list->ha[i]);
        printf("i = %d   ",i);
        while ( s->next!=NULL ){
            /* code */
            printf(" %d  ",s->next->key);
            s = s->next;
        }
        printf("\n");
    }
    return 0;
}
